<template>
  <view class="container">
    <!-- 页面标题 - 固定在顶部 -->
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#333"></FeatherIcon>
      </view>
      <text class="page-title">我的帖子</text>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 帖子列表 -->
      <scroll-view
        scroll-y
        class="scroll-container"
        @scrolltolower="loadMore"
        refresher-enabled
        :refresher-triggered="refresherTriggered"
        @refresherrefresh="handleRefresh"
        refresher-threshold="80"
        refresher-background="#f5f5f5"
      >
        <!-- 加载中状态 -->
        <view v-if="loading && articles.length === 0" class="loading-container">
          <FeatherIcon
            name="loader"
            size="42"
            color="#999"
            class="loading-icon"
          />
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空数据状态 -->
        <view v-else-if="articles.length === 0" class="empty-container">
          <FeatherIcon name="inbox" size="64" color="#999" />
          <text class="empty-text">暂无数据，点击刷新</text>
          <button
            size="mini"
            type="default"
            @click="reload"
            class="refresh-btn"
          >
            刷新
          </button>
        </view>

        <!-- 帖子列表 -->
        <view v-else class="article-list">
          <view
            v-for="article in articles"
            :key="article.oId"
            class="article-item"
            @click="navigateToDetail(article.oId)"
          >
            <view class="article-header">
              <image
                class="author-avatar"
                :src="
                  article.articleAuthor?.userAvatarURL ||
                  '/static/default-avatar.png'
                "
                mode="aspectFill"
              ></image>
              <view class="article-meta">
                <text class="author-name">{{
                  article.articleAuthor?.userNickname || userName
                }}</text>
                <text class="publish-time">{{ article.timeAgo }}</text>
              </view>
            </view>

            <view class="article-content">
              <text class="article-title">{{ article.articleTitle }}</text>
              <text class="article-summary">{{
                formatSummary(
                  article.articlePreviewContent || article.articleContent
                )
              }}</text>

              <!-- 帖子图片 -->
              <image
                v-if="article.articleThumbnailURL"
                :src="article.articleThumbnailURL"
                mode="aspectFill"
                class="article-image"
              ></image>
            </view>

            <view class="article-footer">
              <view
                class="article-tags"
                v-if="article.articleTags && article.articleTags.length > 0"
              >
                <text
                  class="tag"
                  v-for="(tag, tagIndex) in formatTags(article.articleTags)"
                  :key="tagIndex"
                  >{{ tag }}</text
                >
              </view>
              <view class="stat-group">
                <view class="stat-item">
                  <FeatherIcon name="eye" size="16" color="#999" />
                  <text class="stat-value">{{ article.articleViewCount }}</text>
                </view>
                <view class="stat-item">
                  <FeatherIcon name="message-circle" size="16" color="#999" />
                  <text class="stat-value">{{
                    article.articleCommentCount
                  }}</text>
                </view>
                <view class="stat-item">
                  <FeatherIcon name="thumbs-up" size="16" color="#999" />
                  <text class="stat-value">{{ article.articleGoodCnt }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多区域 -->
        <view class="loading-more" v-if="articles.length > 0">
          <view class="loading-content" v-if="loading">
            <FeatherIcon
              name="loader"
              size="36"
              color="#999"
              class="loading-icon"
            />
            <text>加载中...</text>
          </view>
          <view class="loading-content" v-else-if="!hasMore">
            <text>已经到底了~</text>
          </view>
          <view class="loading-content" v-else @click="loadMore">
            <FeatherIcon name="more-horizontal" size="36" color="#999" />
            <text class="load-more-text">点击加载更多</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { articleApi } from "@/api/modules/article";
import { formatDate, timeAgo, htmlToText } from "@/utils/common.js";
import FeatherIcon from "@/components/FeatherIcon.vue";
import api from "@/api";

const articles = ref([]);
const loading = ref(true);
const page = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const refresherTriggered = ref(false);

// 获取页面参数
const userName = ref("");

onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const option = currentPage.options || {};

  console.log("页面参数:", option);
  if (option && option.userName) {
    userName.value = option.userName;
  } else {
    // 获取当前登录用户信息
    const userInfo = uni.getStorageSync("userInfo");
    if (userInfo) {
      userName.value = userInfo.userName || userInfo.user_name;
    }
  }

  // 加载帖子
  if (userName.value) {
    fetchArticles();
  } else {
    // 如果从本地存储获取不到用户名，尝试从全局API获取当前用户信息
    try {
      api.user
        .getCurrentUser()
        .then((res) => {
          if (res && res.code === 0 && res.data) {
            userName.value = res.data.userName;
            fetchArticles();
          } else {
            uni.showToast({
              title: "无法获取用户信息",
              icon: "none",
            });
          }
        })
        .catch((err) => {
          console.error("获取用户信息失败", err);
          uni.showToast({
            title: "无法获取用户信息",
            icon: "none",
          });
        });
    } catch (e) {
      console.error("获取当前用户失败", e);
      uni.showToast({
        title: "无法获取用户名",
        icon: "none",
      });
    }
  }
});

// 获取用户帖子列表
const fetchArticles = async () => {
  try {
    loading.value = true;

    const response = await articleApi.getUserArticles(
      userName.value,
      page.value,
      pageSize.value
    );

    if (response && response.code === 0) {
      const data = response.data || {};
      const articleList = data.articles || [];
      if (page.value === 1) {
        articles.value = articleList;
      } else {
        articles.value = [...articles.value, ...articleList];
      }

      // 判断是否还有更多数据
      hasMore.value = articleList.length >= pageSize.value;
    } else {
      uni.showToast({
        title: response?.msg || "获取帖子失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取帖子列表失败", error);
    uni.showToast({
      title: "获取帖子失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
    // 如果是下拉刷新，结束刷新状态
    if (refresherTriggered.value) {
      setTimeout(() => {
        refresherTriggered.value = false;
      }, 500);
    }
  }
};

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    page.value++;
    fetchArticles();
  }
};

// 下拉刷新处理
const handleRefresh = async () => {
  try {
    refresherTriggered.value = true;
    // 重置页码和数据
    page.value = 1;
    hasMore.value = true;
    // 重新加载数据
    await fetchArticles();
  } catch (error) {
    console.error("刷新出错:", error);
  }
};

// 重新加载
const reload = () => {
  page.value = 1;
  hasMore.value = true;
  fetchArticles();
};

// 格式化文章摘要
const formatSummary = (html) => {
  return htmlToText(html, 100);
};

// 格式化标签
const formatTags = (tagString) => {
  if (!tagString) return [];
  return tagString.split(",").slice(0, 3); // 最多显示3个标签
};

// 跳转到文章详情页
const navigateToDetail = (articleId) => {
  uni.navigateTo({
    url: `/pages/article/detail?id=${articleId}`,
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px 15px;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;

  .back-btn {
    position: absolute;
    left: 20px;
    padding: 10rpx;
    padding-bottom: 0;
  }

  .page-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.content-area {
  padding-top: 80px; /* 为固定的header腾出空间 */
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 80px); /* 减去header的高度 */
}

.scroll-container {
  flex: 1;
  height: 100%;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .loading-icon {
    animation: rotate 1s linear infinite;
  }

  .loading-text,
  .empty-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }

  .refresh-btn {
    margin-top: 20rpx;
  }
}

.article-list {
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;

  .article-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }

  .article-header {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .author-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 16rpx;
      border: 2rpx solid #f0f0f0;
    }

    .article-meta {
      display: flex;
      flex-direction: column;
    }

    .author-name {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }

    .publish-time {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }

  .article-content {
    margin-bottom: 16rpx;

    .article-title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 12rpx;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .article-summary {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .article-image {
      width: 100%;
      height: 320rpx;
      border-radius: 12rpx;
      margin-top: 16rpx;
      background-color: #f0f0f0;
    }
  }

  .article-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #f5f5f5;
    padding-top: 16rpx;

    .article-tags {
      display: flex;
      flex-wrap: wrap;

      .tag {
        font-size: 22rpx;
        color: #ff9800;
        background-color: rgba(255, 152, 0, 0.1);
        padding: 4rpx 12rpx;
        border-radius: 6rpx;
        margin-right: 10rpx;
      }
    }

    .stat-group {
      display: flex;
      align-items: center;
    }

    .stat-item {
      display: flex;
      align-items: center;
      margin-right: 24rpx;

      &:last-child {
        margin-right: 0;
      }

      .stat-value {
        font-size: 22rpx;
        color: #999;
        margin-left: 6rpx;
      }
    }
  }
}

.loading-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 28rpx;

  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20rpx 0;
  }

  .loading-icon {
    animation: rotate 1s linear infinite;
  }

  .load-more-text {
    color: #0072ff;
    margin-top: 10rpx;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
